package com.chenyun.common.utils;
import com.chenyun.common.annotation.CacheType;
import com.chenyun.common.baseinterface.BaseCacheInterface;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 缓存键的管理类
 * 通过spring的多注入模式   BaseCacheInterface 是基类,所有配置缓存键的类都必须继承此类
 *
 */
@Component
public class CacheTypeUtil {
    public CacheTypeUtil(List<BaseCacheInterface> cacheInterfaces) {
        CacheTypeUtil.cacheInterfaces = cacheInterfaces;
    }

    private static List<BaseCacheInterface> cacheInterfaces;

    /**
     * 获取所有的缓存组
     */
    public static List<Map<String, Object>> getCacheTypes() {
        List<Map<String, Object>> mapList = Lists.newArrayList();

        cacheInterfaces.forEach(p -> {

            String name = "";
            System.out.println(p.getClass());
            Class<? extends BaseCacheInterface> aClass = p.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            System.out.println(declaredFields);
            CacheType annotation = aClass.getAnnotation(CacheType.class);
            if (annotation != null) {
                name = annotation.value();
            } else {
                name = aClass.getName();
            }

            List<Map<String, String>> childrens = Lists.newArrayList();
            for (int i = 0; i < declaredFields.length; i++) {
                String key = declaredFields[i].getName();
                CacheType annotation1 = declaredFields[i].getAnnotation(CacheType.class);
                String value = annotation1.value();
                HashMap<String, String> map = new HashMap<String, String>() {{
                    put("key", key);
                    put("value", value);
                }};
                childrens.add(map);
            }
            String finalName = name;
            Map<String, Object> listMap = new HashMap<String, Object>() {{
                put("name", finalName);
                put("children", childrens);
            }};
            mapList.add(listMap);
        });

        return mapList;
    }


}
